package com.xinfu.newproject.activity;

import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import com.fanneng.android.web.file.FileReaderView;
import com.github.barteksc.pdfviewer.PDFView;
import com.xinfu.newproject.R;
import com.xinfu.newproject.base.BaseActivity;
import com.xinfu.newproject.util.NoticeEvent;
import com.xinfu.newproject.util.rxHttp.HttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

public class SuperWebActivity extends BaseActivity {

    @BindView(R.id.activity_super_web_ll)
    LinearLayout superLL;

    private String mInvoiceDir;
    private String imgUrl;

    @BindView(R.id.activity_super_web_pdf)
    PDFView pdfView;

    @BindView(R.id.documentReaderView)
    FileReaderView fileReaderView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_superweb);
        ButterKnife.bind(this);
        registerBack();
        EventBus.getDefault().register(this);
        setActivityTitle("发票");
        initViewBind();
        initLisener();
    }

    private void initLisener() {

    }

    private void initViewBind() {
//        FragmentManager fragmentManager = getSupportFragmentManager();
//        FragmentTransaction ft = fragmentManager.beginTransaction();
//        ft.add(R.id.activity_super_web_fl, new SuperWebFragment());
//        ft.commitAllowingStateLoss();
        getData();
    }


    private void getData() {
        try {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath();
            mInvoiceDir = path + File.separator + "畅e生活发票下载";
            File file = new File(mInvoiceDir);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        imgUrl = getIntent().getExtras().getString("response");
        //下载显示pdf
        downloadImgSave(imgUrl, true);

    }

    private String filename;

    private void downloadImgSave(String imgUrlTarget, final boolean showToast) {
        filename = imgUrlTarget;
        if (imgUrlTarget.length() > 16) {
            filename = imgUrlTarget.substring(imgUrlTarget.length() - 5, imgUrlTarget.length());
        }
        //判断文件存在不
        File file = new File(mInvoiceDir + File.separator + filename + ".pdf");
        if (file.exists()) {
//            pdfView.fromFile(file)
//                    .defaultPage(1)//默认展示第一页
//                    .onPageChange(SuperWebActivity.this)//监听页面切换
//                    .load();
//            File file1 = new File("/storage/emulated/0/畅e生活发票下载/b.pdf");
            fileReaderView.show(file.getAbsolutePath());
            return;
        } else {
//        File file1 = new File("/storage/emulated/0/畅e生活发票下载/c.pdf");

            Log.i("testOne", imgUrlTarget + "测试=" + mInvoiceDir + "测试=" + filename);
            downFile(getIntent().getExtras().getString("response"), mInvoiceDir, filename + ".pdf");
        }
    }

    public void downFile(String url, final String fileDir, final String fileName) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = HttpUtils.getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(fileDir, fileName);
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                    }
                    fos.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (is != null) is.close();
                    if (fos != null) fos.close();
                }
//                pdfView.fromFile(new File(mInvoiceDir + File.separator + filename + ".pdf"))
//                        .defaultPage(1)//默认展示第一页
//                        .onPageChange(SuperWebActivity.this)//监听页面切换
//                        .load();

                EventBus.getDefault().post(new NoticeEvent("fileReader", mInvoiceDir + File.separator + filename + ".pdf"));
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁界面的时候一定要加上，否则后面加载文件会发生异常。
        fileReaderView.stop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMsg(NoticeEvent event) {
        if (event.getCls().equals("fileReader")) {
            File file1 = new File(event.getData().toString());
            fileReaderView.show(file1.getAbsolutePath());
        }
    }
}
